//! 数据包格式

#![no_std]

pub use unmp_id::Id;
pub use unmp_link::prelude::{Bytes, BytesMut};

/// 版本号
pub(crate) const VERSION: u8 = 0x03;
/// 数据包最小长度(数据长度为0)
pub(crate) const MIN_LEN: usize = 8;

/// 数据包头
#[derive(Debug, Clone)]
pub struct Header {
    /// 序列号
    pub sn: u8,
    /// 源地址
    pub src: Id,
    /// 目标地址
    pub dst: Id,
    /// 重要数据会传遍所有网络，直至ttl失效，常用于设备发现
    pub important: bool,
    /// 生存时间(0x0~0xF)
    pub ttl: u8,
    /// 协议类型
    pub protocol: u8,
}
/// 数据包
#[derive(Debug)]
pub struct Packet {
    /// 数据包头
    pub head: Header,
    /// 负载数据
    pub data: Bytes,
}

/// 编码数据包
pub fn encode(packet: &Packet) -> Bytes {
    let Packet { head, data } = packet;
    let mut buf = BytesMut::new();
    buf.extend([VERSION]);
    buf.extend([head.sn]);
    buf.extend_from_slice(&head.src);
    buf.extend_from_slice(&head.dst);
    let ttl = if head.ttl > 0xF { 0xF } else { head.ttl };
    buf.extend([(head.important as u8) << 4 | ttl]);
    buf.extend([head.protocol]);
    buf.extend_from_slice(data);
    buf.freeze()
}
/// 解码数据包
pub fn decode(mut buf: Bytes) -> Result<Packet, ()> {
    let buf_len = buf.len();
    if buf_len < MIN_LEN {
        return Err(());
    }

    if buf[0] == VERSION {
        let sn = buf[1];
        let (src, rest) = Id::split_buf(&buf[2..]);
        let (dst, rest) = Id::split_buf(rest);
        let important = (rest[0] & 0x10) != 0;
        let ttl = rest[0] & 0x0F;
        let protocol = rest[1];
        let data = buf.split_off(2 + src.len() + dst.len() + 2);
        let head = Header {
            sn,
            src,
            dst,
            important,
            ttl,
            protocol,
        };
        let packet = Packet { head, data };
        return Ok(packet);
    } else {
        return Err(());
    }
}
